package com.duoduo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.duoduo.constant.MessageConstant;
import com.duoduo.constant.StatusConstant;
import com.duoduo.dto.SetmealDTO;
import com.duoduo.dto.SetmealPageQueryDTO;
import com.duoduo.entity.Dish;
import com.duoduo.entity.Setmeal;
import com.duoduo.entity.SetmealDish;
import com.duoduo.exception.DeletionNotAllowedException;
import com.duoduo.exception.SetmealEnableFailedException;
import com.duoduo.mapper.DishMapper;
import com.duoduo.mapper.SetmealDishMapper;
import com.duoduo.mapper.SetmealMapper;
import com.duoduo.result.PageResult;
import com.duoduo.service.SetmealService;
import com.duoduo.vo.DishItemVO;
import com.duoduo.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 分页查询
     *   注意还要返回categoryName
     * @param setmealPageQueryDTO：含page，pageSize和查询条件name，categoryId，status
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.pageQuery(setmealPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增套餐
     *  创建时间的倒序排列,新增套餐默认为停售状态
     *  要往setmeal，setmeal_dish表添加，
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void save(SetmealDTO setmealDTO) {
        // 添加套餐信息到setmeal表
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);  // 默认为停售
        setmealMapper.insert(setmeal);  // 要获得插入数据的主键id到setmeal（而不是setmealDTO）

        // 添加套餐对应的多个菜品到setmeal_dish表
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        // 为每个dish赋setmealID值
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmeal.getId());
        });
        // 批量插入
        setmealDishMapper.insertBatch(setmealDishes);

    }

    /**
     * 批量删除套餐
     *  在售状态下，不可删除套餐
     *  别忘记删除套餐菜品关系表setmeal_dish中的数据
     * @param ids: 如 1,2,3
     * @return
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        // 判断状态是否处于在售
        List<Setmeal> setmeals = setmealMapper.getByIds(ids);
        for (Setmeal setmeal : setmeals) {
            if (setmeal.getStatus() == StatusConstant.ENABLE){
                //在售中的套餐不能删除
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        // 删除套餐表中的数据
        setmealMapper.deleteByIds(ids);
        // 删除套餐菜品关系表中的数据
        for (Long id : ids) {
            setmealDishMapper.deleteBySetmealId(id);
        }
    }

    /**
     * 根据id查询套餐和套餐菜品关系
     * @param id
     * @return
     */
    @Override
    @Transactional
    public SetmealVO getById(Long id) {
        SetmealVO setmealVO = new SetmealVO();
        // 查询封装套餐信息
        Setmeal setmeal =  setmealMapper.getById(id);
        BeanUtils.copyProperties(setmeal, setmealVO);

        // 查询封装套餐下的菜品信息
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(id);
        setmealVO.setSetmealDishes(setmealDishes);

        return setmealVO;
    }

    /**
     * 修改套餐和对应的菜品信息
     * @param setmealDTO
     */
    @Override
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        // 修改套餐信息
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);

        // 修改套餐对应的菜品信息
        // 先删除对应菜品
        setmealDishMapper.deleteBySetmealId(setmealDTO.getId());

        // 再添加对应菜品
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        // 为每个菜品设置SetmealId
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDTO.getId());
        }
        setmealDishMapper.insertBatch(setmealDishes);


    }

    /**
     * 启售停售套餐
     *  套餐内如果有停售菜品，则套餐无法上架
     * @param status
     * @param setmealId
     */
    @Override
    @Transactional
    public void  startOrStop(Integer status, Long setmealId) {
        // 当设置套餐为启售时，若关联的菜品有停售菜品，则报错
        if(status == StatusConstant.ENABLE){
            // 查看关联的菜品信息
            // 或者多表查询：select d.* from dish d left join setmeal_dish sd on d.id = sd.dish_id where sd.setmeal_id = setmealId
            List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(setmealId);

            // （要先判断setmealDishes是否为空，否则在setmealDish.getDishId()可能会报空指针异常）
            if (setmealDishes != null && setmealDishes.size() > 0){
                for (SetmealDish setmealDish : setmealDishes) {
                    Long dishId = setmealDish.getDishId();
                    // 判断是否有停售菜品
                    Dish dish = dishMapper.getById(dishId);
                    if(dish.getStatus() == StatusConstant.DISABLE){
                        // 有停售的菜品
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
            }
        }

        // 更新套餐信息
        Setmeal setmeal = setmealMapper.getById(setmealId);
        setmeal.setStatus(status);
        setmealMapper.update(setmeal);
    }


    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }


    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
